<!--
 * @Description: 
 * @Author: 胡涛
 * @Date: 2023-09-11 21:21:30
 * @LastEditors: 胡涛
 * @LastEditTime: 2024-01-21 19:15:22
-->
<template>
  <div class="page-wrapper">
    <div class="toolbar">
      <div class="breadcrumb">
        <a-breadcrumb>
          <a-breadcrumb-item>资源管理</a-breadcrumb-item>
          <a-breadcrumb-item>资源文件管理</a-breadcrumb-item>
        </a-breadcrumb>
      </div>
      <a-space>
        <a-select
          v-model:value="searchModel.BucketName"
          @change="
            () => {
              getDirItems();
              queryList();
            }
          "
        >
          <a-select-option
            v-for="item in bucketItems"
            :key="item.id"
            :value="item.id"
            >{{ item.description }}</a-select-option
          >
        </a-select>
        <a-button
          type="primary"
          @click="onHandleCreate"
          v-if="currentDirPath"
          v-auth="'Create'"
        >
          <template #icon>
            <PlusOutlined />
          </template>
          上传资源
        </a-button>
        <a-button type="primary" :loading="loading" @click="queryList">
          <template #icon>
            <SyncOutlined />
          </template>
          刷新
        </a-button>
        <!-- <a-button type="primary">
          <template #icon>
            <ExportOutlined />
          </template>
          导出
        </a-button> -->
      </a-space>
    </div>
    <div class="container">
      <div class="dir">
        <a-breadcrumb>
          <span class="label"> 资源目录：</span>
          <a-breadcrumb-item
            v-for="(item, index) in resourcePaths"
            :key="index"
            >{{ item }}</a-breadcrumb-item
          >
        </a-breadcrumb>
      </div>
      <div class="file-wrapper">
        <div class="file-dir">
          <a-directory-tree
            :treeData="dirItems"
            :selectedKeys="[currentDirPath]"
            :fieldNames="{
              title: 'dirName',
              key: 'dirPath',
              children: 'children',
            }"
            @select="onDirSelect"
          ></a-directory-tree>
        </div>
        <div class="file-table">
          <div class="table">
            <a-table
              bordered sticky
              :columns="columns"
              :row-key="(record) => record.id"
              :data-source="dataSource"
              :pagination="pagination"
              :loading="loading"
              @change="handleTableChange"
            >
            </a-table>
          </div>
        </div>
      </div>
    </div>
  </div>
  <upload-view
    v-model:visible="popupModel.visible"
    :dir="currentDir"
    v-if="popupModel.visible"
    @close="queryList"
  />
  <preview-file
    v-model:visible="previewModel.visible"
    :id="previewModel.id"
    :fileName="previewModel.fileName"
    v-if="previewModel.visible"
  />
</template>

<script lang="ts" setup>
import {
  PlusOutlined,
  ExportOutlined,
  SyncOutlined,
  EditOutlined,
  DownloadOutlined,
} from "@ant-design/icons-vue";
import { useListPage } from "@/helpers/pages";
import bucketApi from "@/api/resource/bucket";
import dirApi from "@/api/resource/dirResource";
import api from "@/api/resource/fileResource";
import {
  BucketDto,
  DirResourceDto,
  FileResourceDto,
} from "@/api/resource/types";
import { checkActionStyle } from "@/helpers";
import { h, onMounted, ref, watch } from "vue";
import { PaginationConfig } from "ant-design-vue/es/pagination";
import { Button, ButtonGroup, message, Popconfirm } from "ant-design-vue";
import UploadView from "./Upload.vue";
import { enumName, enums } from "@/plugins/enums";
import dayjs from "dayjs";
import PreviewFile from "@/components/preview-file/Index.vue";

const {
  loading,
  dataSource,
  columns,
  pagination,
  popupModel,
  searchModel,
  createQueryModel,
  onHandleCreate,
  onHandleUpdate,
} = useListPage<FileResourceDto, string>({
  searchModel: {
    Name: "",
    ParentId: "",
    BucketName: "",
  },
  columns: [
    {
      dataIndex: "fileName",
      title: "文件名",
    },
    {
      dataIndex: "dirPath",
      title: "所在路径",
    },
    {
      dataIndex: "fileType",
      title: "文件类型",
      width: 80,
      customRender: ({ value }) => {
        return enumName(enums.FileType, value);
      },
    },
    {
      dataIndex: "fileSize",
      title: "文件大小",
      width: 120,
      customRender: ({ value }) => {
        return Math.ceil(value / 1024.0) + "KB";
      },
    },
    {
      dataIndex: "creationTime",
      width: 160,
      align: "center",
      title: "上传时间",
      customRender: ({ value }) => {
        return dayjs(value).format("YYYY-MM-DD HH:mm");
      },
    },
    {
      dataIndex: "isPublic",
      width: 80,
      align: "center",
      title: "访问权限",
      customRender: ({ value }) => {
        return value ? "公开" : "私用";
      },
    },
    {
      dataIndex: "action",
      title: "操作",
      width: 150,
      customRender: ({ record }: any) => {
        return h(ButtonGroup, [
          h(
            Button,
            {
              type: "primary",
              size: "small",
              ghost: true,
              style: checkActionStyle("View"),
              onClick() {
                previewModel.value = {
                  visible: true,
                  id: record.id,
                  fileName: record.fileName,
                };
              },
            },
            {
              icon() {
                return [h(EditOutlined)];
              },
              default() {
                return "查看";
              },
            }
          ),
          h(
            Button,
            {
              type: "primary",
              size: "small",
              ghost: true,
              style: checkActionStyle("View"),
              onClick: () => onDownload(record),
            },
            {
              icon() {
                return [h(DownloadOutlined)];
              },
              default() {
                return "下载";
              },
            }
          ),
        ]);
      },
    },
  ],
});
const resourcePaths = ref<Array<string>>([]);
const bucketItems = ref<Array<BucketDto>>([]);
const dirItems = ref<Array<DirResourceDto>>([]);
const currentDirPath = ref<string>("");
const currentDir = ref<DirResourceDto>();

const previewModel = ref<{ visible: boolean; id: string; fileName: string }>({
  id: "",
  fileName: "",
  visible: false,
});

const onDownload = async (item: FileResourceDto) => {
  let originUrl = `/api/file/download/${item.id}`;
  downloadFile(originUrl, item.fileName);
};

const downloadFile = (url: string, fileName: string) => {
  var link = document.createElement("a");
  link.style.display = "none";
  link.href = url;
  link.target = "_blank";
  link.setAttribute("download", fileName);
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};
const queryList = async () => {
  loading.value = true;
  searchModel.value.DirPath = currentDirPath.value || "";
  let result = await api.getList(createQueryModel());
  dataSource.value = result.items;
  pagination.total = result.totalCount;
  loading.value = false;
};

/**
 * 获取所有资源块
 */
const getBucketItems = async () => {
  bucketItems.value = await await bucketApi.getAllList({ Status: true });
  if (bucketItems.value.length) {
    searchModel.value.BucketName = bucketItems.value[0].id;
  }
};

/**
 * 获取指定资源块的资源目录
 */
const getDirItems = async () => {
  dirItems.value = await await dirApi.getTreeList({
    BucketName: searchModel.value.BucketName,
  });
  dirItems.value.splice(0, 0, {
    parentId: "",
    dirName: "根目录",
    dirPath: "",
    bucketName: searchModel.value.BucketName,
    folderIcon: "",
    description: "根目录",
    remarks: "",
  });

  currentDirPath.value = dirItems.value[0].dirPath;
  currentDir.value = dirItems.value[0];
  resourcePaths.value = ["根目录"];
};

const handleTableChange = (pageConfig: PaginationConfig, filters: any) => {
  pagination.current = pageConfig.current;
  queryList();
};

const onDirSelect = (selectedKeys: Array<string>, e: any) => {
  if (selectedKeys.length) {
    currentDirPath.value = selectedKeys[0];
    currentDir.value = e.node.dataRef;
  } else {
    currentDir.value = null;
    currentDirPath.value = "";
  }
  if (currentDirPath.value) {
    resourcePaths.value = currentDirPath.value.split("/");
  } else {
    resourcePaths.value = ["根目录"];
  }
  queryList();
};

onMounted(async () => {
  await getBucketItems();
  await getDirItems();
  queryList();
});
</script>

<style lang="less" scoped>
.container {
  overflow: hidden;
  .dir {
    height: 50px;
    padding: 10px 0;
    .label {
      color: #333;
      padding-right: 5px;
    }
  }

  .file {
    &-wrapper {
      display: flex;
      flex: 1;
      height: calc(100% - 50px);
    }

    &-dir {
      width: 240px;
      flex: none;
      padding: 8px;
      border: 1px solid #eee;
      margin-right: 8px;
      background: #fbfbfb;
    }

    &-table {
      flex: 1;
      height: 100%;
    }
  }

  .table {
    flex: 1;
  }
}
</style>
